#    Copyright (C) 2008 William Waites
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
Support for the CAIDA IPv4 Routed /24 AS-Links Dataset

For more information and where to get the data see,
http://www.caida.org/data/active/ipv4_routed_topology_aslinks_dataset.xml
"""

from adjacencies.graph import AS
import gzip
import re

__all__ = ["load_aslinks"]

aslinkre = re.compile(r"^(D|I)[ \t]+([0-9]+)[ \t]([0-9]+)[ \t]+.*$")
def load_aslinks(fname, mesh, indirect=False):
	"""
	Load adjacencies from the given file into the mesh. Only loads 
	direct links unless the "indirect" keyword argument is set to a
	True value. AS_SETS and inconsistent origins are ignored.
	"""
	fp = gzip.open(fname)
	for line in fp.readlines():
		m = aslinkre.match(line)
		if not m: continue
		type, as1, as2 = m.groups()
		if type == "D" or indirect == True:
			mesh.add_edge(AS(int(as1)), AS(int(as2)))
